package xc;

import java.util.Random;
//String result = String.format("%.2f", num);
public class demo5 {
    public static class my_thread extends Thread{
        static double money = 100;
        static int cnt = 3;
        static final double MIN = 0.01;
//      100块红包分成3个，5个人来抢
        public void run(){
            synchronized (my_thread.class){
                if(cnt==0){
                    System.out.println(getName()+"红包没抢到。");
                } else{
                    //最后一个红包
                    if(cnt==1){
                        double price = money;
                        cnt--;
                        System.out.println(getName()+"抢到了"+ String.format("%.2f", price));
                    } else{
                        Random r = new Random();
                        double price = r.nextDouble(money - cnt*(MIN));
                        if(price<=0){
                            price = MIN;
                        }
                        money = money - price;
                        cnt--;
                        System.out.println(getName()+"抢到了" + String.format("%.2f",price));
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        my_thread t1 = new my_thread();
        my_thread t2 = new my_thread();
        my_thread t3 = new my_thread();
        my_thread t4 = new my_thread();

        t1.setName("t1");
        t2.setName("t2");
        t3.setName("t3");
        t4.setName("t4");

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
